package com.mingqijia.gassafety.webserver.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.entity.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.db.entity.vo.GetCondtionListVo;
import com.mingqijia.gassafety.db.entity.vo.HistoryBrokenVO;
import com.mingqijia.gassafety.db.entity.vo.LatestLogListVO;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConfiguration;
import com.mingqijia.gassafety.db.influxdb.config.InfluxDBConnect;
import com.mingqijia.gassafety.db.mapper.HistoryBrokenMapper;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.UserFuncCodePermissionDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.HeaderUtil;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageColumns;
import com.mingqijia.gassafety.shared.utils.commonUtils.PageUtil;
import com.mingqijia.gassafety.webserver.request.LatestLogListRequest;
import com.mingqijia.gassafety.webserver.request.RecordLogRequest;
import com.mingqijia.gassafety.webserver.response.BrokenLogResponse;
import com.mingqijia.gassafety.webserver.response.CompanyResponse;
import com.mingqijia.gassafety.webserver.response.FieldListShowResponse;
import com.mingqijia.gassafety.webserver.response.HistoryAlarmAndBrokenResponse;
import com.mingqijia.gassafety.webserver.response.OrganizationResponse;
import com.mingqijia.gassafety.webserver.response.sk.AlarmSupplierListVo;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkSupplierListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.webserver.service.cmp.EquipmentCmpService;
import lombok.extern.slf4j.Slf4j;
import org.influxdb.dto.QueryResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mingqijia.gassafety.shared.constant.Constants.ORG_MAP_SUBSCODE;

/**
 * <p>
 * 报警器设备故障记录 服务实现类
 * </p>
 *
 * @author wanghai
 * @since 2022-08-08
 */
@Service
@Slf4j
public class HistoryBrokenServiceImpl extends ServiceImpl<HistoryBrokenMapper, HistoryBroken> implements HistoryBrokenService {
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    InfluxDBConfiguration influxDBConfiguration;
    @Autowired
    ConsumerService consumerService;
    @Autowired
    ConfigureHolder holder;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    HeaderUtil headerUtil;
    @Autowired
    OrganizationService organizationService;
    @Autowired
    FieldListShowService fieldListShowService;
    @Autowired
    EquipmentServiceImpl equipmentServiceImpl;
    @Autowired
    CommonService commonService;
    @Autowired
    CompanyService companyService;

    @Autowired
    UserPermissionService userPermissionService;

    @Autowired
    EquipmentCmpService equipmentCmpService;

    @Override
    public PageUtil<BrokenLogResponse> getList(RecordLogRequest req) {

        List<BrokenLogResponse> resultList = new ArrayList<>();
        LatestLogListVO vo = new LatestLogListVO();
        BeanUtils.copyProperties(req, vo);

        String spId = ApplicationUtils.getWorkingSpId();
        //1.1所属组织
        List<String> spIds = organizationService.getSpIds(spId);
        if (!StringUtils.isEmpty(req.getSpId())) {
            //如果查询条件不为空，按查询条件来
            spIds.clear();
            spIds.add(req.getSpId());
        }
        vo.setSpIds(spIds);

        Page<HistoryBrokenVO> page = PageHelper.startPage(req.getPage(), req.getPageSize());
        List<HistoryBrokenVO> list = new ArrayList<>();
        //页面不完全返回结果封装
        if (req.getTemplateType() == null) {
            req.setTemplateType(headerUtil.getTemplateType());
        }

        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        vo.setFuncCodes(userFuncCodePermission.getFuncCodes());

        if (TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType()) {
            list = baseMapper.getVccRecord(vo);
        } else if (TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()) {
            list = baseMapper.getAsstRecord(vo);
        }
        //查询组织架构名称
        List<CompanyResponse> companyNameList = companyService.queryCompanyNameList(spIds);
        Map<String, String> companyNameMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(companyNameList)) {
            companyNameMap = companyNameList.stream().collect(Collectors.toMap(CompanyResponse::getSpId, CompanyResponse::getName));
        }
        //批量查询字典
        List<DictionaryItemRespDTO> orgMapSubsCodeList = holder.getDictionaryByKey(ORG_MAP_SUBSCODE);
        Map<String, String> orgSubsCodeMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(orgMapSubsCodeList)) {
            orgSubsCodeMap = orgMapSubsCodeList.stream().collect(Collectors.toMap(DictionaryItemRespDTO::getDescription, DictionaryItemRespDTO::getCompanyName));
        }
        if (!CollectionUtils.isEmpty(list)) {
            //设备类型列表
            List<DictionaryItemRespDTO> equipmentTypeDictList = holder.getDictionaryByKey(
                    EquipmentType.DICT_CODE);
            //行业类型列表
            List<DictionaryItemRespDTO> industryTypeDictList = holder.getIndustryTypeZJ(spIds);
            //设备厂商列表
            ConsoleSkSupplierListResponse supplierList = equipmentCmpService.supplierListRequest();
            log.info("调用厨房查询厂商接口返回：{}", supplierList);
            List<AlarmSupplierListVo> supplierListVos = new ArrayList<>();
            if (supplierList != null && supplierList.getCode() == 0 && supplierList.getData() != null && org.apache.commons.collections.CollectionUtils.isNotEmpty(supplierList.getData())) {
                supplierListVos = supplierList.getData();
            }
            //运营商列表
            List<DictionaryItemRespDTO> operatorList = holder.getDictionaryByKey(Constants.OPERATOR_CODE);
            //组织名称列表
            List<OrganizationResponse> organizationList = organizationService.getList(ApplicationUtils.getWorkingSpId());
            List<String> query = equipmentServiceImpl.getQueryParams();
            List<Map<String, String>> customerCode = equipmentServiceImpl.dictMap(null, query, null);
            for (HistoryBrokenVO historyBrokenVO : list) {
                BrokenLogResponse response = new BrokenLogResponse();
                BeanUtils.copyProperties(historyBrokenVO, response);
                response.setValveInfoId(historyBrokenVO.getValveInfoId());
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(historyBrokenVO.getOrgCode()) && orgSubsCodeMap.containsKey(historyBrokenVO.getOrgCode())) {
                    response.setCompanyName(orgSubsCodeMap.get(historyBrokenVO.getOrgCode()));
                } else {
                    if (companyNameMap.containsKey(historyBrokenVO.getSpId())) {
                        response.setCompanyName(companyNameMap.get(historyBrokenVO.getSpId()));
                    }
                }
                //处理人信息
                if (!StringUtils.isEmpty(historyBrokenVO.getUserName()) && !StringUtils.isEmpty(historyBrokenVO.getUserAccount())) {
                    response.setUserInfo(historyBrokenVO.getUserName() + "(" + historyBrokenVO.getUserAccount() + ")");
                } else if (StringUtils.isEmpty(historyBrokenVO.getUserName()) && !StringUtils.isEmpty(historyBrokenVO.getUserAccount())) {
                    response.setUserInfo(historyBrokenVO.getUserAccount());
                } else if (!StringUtils.isEmpty(historyBrokenVO.getUserName()) && StringUtils.isEmpty(historyBrokenVO.getUserAccount())) {
                    response.setUserInfo(historyBrokenVO.getUserName());
                }
                //处理状态
                response.setAppealStatusMsg(AppealStateEnum.matcher(historyBrokenVO.getAppealStatus()).getMsg());
                //设置设备类型名称
                response.setEquipmentTypeName(getName(equipmentTypeDictList, historyBrokenVO.getEquipmentType()));
                //设置行业类型名称
                response.setIndustryTypeName(getName(industryTypeDictList, historyBrokenVO.getIndustryType()));
                //运营商
                response.setOperators(getName(operatorList, historyBrokenVO.getOperators()));
                //设置设备厂商
                List<AlarmSupplierListVo> listVos = supplierListVos.stream().filter(a -> a.getAlarmSystemCode().equals(
                        historyBrokenVO.getEquipmentManufacturer())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(listVos)) {
                    response.setEquipmentManufacturer(listVos.get(0).getMsName());
                }
                //紫荆设备 故障原因、联系人手机号
                if (historyBrokenVO.getEquipmentFrom() == Constants.ZJ_EQUIPMENT_FROM) {
                    if (!StringUtils.isEmpty(historyBrokenVO.getBrokenReason())
                            && !StringUtils.isEmpty(historyBrokenVO.getBrokenInfo())) {
                        response.setBrokenReason(historyBrokenVO.getBrokenReason() + ";" + historyBrokenVO.getBrokenInfo());

                    } else if (StringUtils.isEmpty(historyBrokenVO.getBrokenReason())
                            && !StringUtils.isEmpty(historyBrokenVO.getBrokenInfo())) {
                        response.setBrokenReason(historyBrokenVO.getBrokenInfo());
                    }
                    response.setContactPhone(historyBrokenVO.getPhone());
                }
                response.setDetectionType(equipmentServiceImpl.setDetection(query, customerCode, response.getDetectionType()));

                //所属组织
                if (!CollectionUtils.isEmpty(organizationList)) {
                    List<OrganizationResponse> collect = organizationList.stream()
                            .filter(a -> a.getSpId().equals(historyBrokenVO.getSpId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        response.setSpName(collect.get(0).getSpName());
                    }
                }
                //记录中的客户是否是设备上的实时客户
                if(historyBrokenVO.getConsumerId() != 0 && historyBrokenVO.getConsumerId().equals(historyBrokenVO.getLatestConsumerId())){
                    response.setBinded(1);
                }else {
                    response.setBinded(0);
                }
                //设备是否携带电磁阀
                response.setHasValve(historyBrokenVO.getValveInfoId() == 0 ? "-":"有");
                resultList.add(response);
            }
        }
        List<FieldListShowResponse> responses = fieldListShowService.queryListShowByShowStatus(PageListCode.BREAKDOWN_RECORD.getCode(), spId);
        List<String> fields = responses.stream().map(FieldListShowResponse::getFieldCode).collect(Collectors.toList());
        List<String> titles = responses.stream().map(FieldListShowResponse::getFieldName).collect(Collectors.toList());
        List<PageColumns> pageColumns = new ArrayList<>();
        if (TemplateTypeEnum.TEMPLATE_TYPE_1.getCode() == req.getTemplateType()) {
            pageColumns = PageColumnConst.add(titles.toArray(new String[]{}), fields.toArray(new String[]{}),ApplicationUtils.getWorkingSpId());
        } else if (TemplateTypeEnum.TEMPLATE_TYPE_2.getCode() == req.getTemplateType()) {
            pageColumns = PageColumnConst.add(PageColumnConst.BrokenVccUserTitles, PageColumnConst.BrokenVccUserIndices,ApplicationUtils.getWorkingSpId());
        }
        List<Integer> consumerIds= resultList.stream().map(BrokenLogResponse::getConsumerId).collect(Collectors.toList());
        List<Integer> valveInfoIds = list.stream().map(HistoryBrokenVO::getValveInfoId).collect(Collectors.toList());

        commonService.loadFieldAndPackaging(resultList, BrokenLogResponse.class, consumerIds, valveInfoIds, null, spId,PageListCode.BREAKDOWN_RECORD.getCode());
        log.info("historyBroken-resultList:{}", com.alibaba.fastjson.JSONObject.toJSONString(resultList));
        PageUtil pageInfo = new PageUtil<>(req.getPage(), req.getPageSize(), page.getTotal(), resultList, pageColumns);
        return pageInfo;
    }

    private String getName(List<DictionaryItemRespDTO> list, String value) {
        if (!CollectionUtils.isEmpty(list)) {
            List<DictionaryItemRespDTO> respDTOS = list.stream()
                    .filter(dict -> dict.getValue().equals(value)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(respDTOS)) {
                return respDTOS.get(0).getName();
            }
        }
        return null;
    }

    @Override
    public Map<String, Integer> getConditionList() {
        String spId = ApplicationUtils.getWorkingSpId();
        List<String> spIds = organizationService.getSpIds(spId);
        Map<String, Integer> map = new HashMap<>();
        //数据权限
        UserFuncCodePermissionDTO userFuncCodePermission = userPermissionService.getUserDepartPermission(spIds);
        //诉求状态：0待处理 1工单处理中 2已处理 3工单处理完成
        GetCondtionListVo conditionList = this.baseMapper.getConditionList(spIds, userFuncCodePermission.getFuncCodes());
        Integer all = conditionList.getNumber();
        Integer handling = conditionList.getHandling();
        Integer hasHandled = conditionList.getHasHandled();
        Integer finishing = conditionList.getFinishing();
        Integer unclosed = conditionList.getUnclosed();
        Integer closed = conditionList.getClosed();
        Integer handleInstall = conditionList.getHandleInstall();
        Integer handlerTest = conditionList.getHandlerTest();
        Integer unNeedHandle = conditionList.getUnNeedHandle();
        Integer waitHandle = 0;
        if (all == null) {
            all = 0;
        }
        if (handling == null) {
            handling = 0;
        }
        if (hasHandled == null) {
            hasHandled = 0;
        }
        if (finishing == null) {
            finishing = 0;
        }
        if (unclosed == null) {
            unclosed = 0;
        }
        if (closed == null) {
            closed = 0;
        }
        if (handleInstall == null) {
            handleInstall = 0;
        }
        if (handlerTest == null) {
            handlerTest = 0;
        }
        if (unNeedHandle == null) {
            unNeedHandle = 0;
        }
        waitHandle = all - handling - hasHandled - finishing - unclosed - closed - handleInstall - handlerTest - unNeedHandle;

        map.put("未处理", waitHandle);
        map.put("处理中", handling);
        map.put("处理完成", hasHandled + finishing + closed + unclosed + handleInstall+ handlerTest + unNeedHandle);
        return map;

    }



    @Override
    public List<HistoryAlarmAndBrokenResponse> getEffectiveData(Integer customerId) {
//        LambdaQueryWrapper<HistoryBroken> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(HistoryBroken::getIsDeleted, 0)
//                .eq(HistoryBroken::getConsumerId, customerId)
//                .eq(HistoryBroken::getAppealStatus, 0);
//
//        List<HistoryBroken> historyBrokens = this.baseMapper.selectList(queryWrapper);
        List<HistoryBroken> historyBrokens = this.baseMapper.selectByCustomerId(customerId);
        return CollectionUtils.isEmpty(historyBrokens) ? new ArrayList<>() : historyBrokens.stream().map(historyAlarm -> {
            HistoryAlarmAndBrokenResponse response = new HistoryAlarmAndBrokenResponse();
            BeanUtils.copyProperties(historyAlarm, response);
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public PageUtil<BrokenLogResponse> list(RecordLogRequest req) {
        List<BrokenLogResponse> resultList = new ArrayList<>();
        String spId = req.getSpId();
        if (StringUtils.isEmpty(spId)) {
            spId = ApplicationUtils.getWorkingSpId();
        }
        //根据spId换path
        String path = departmentService.getPath(spId);
        //获取数据库连接
        InfluxDBConnect influxDBConnect = influxDBConfiguration.getInfluxDBConnect();
        List<Dtu> equipmentList = new ArrayList<>();
        if (!StringUtils.isEmpty(req.getImei()) || !StringUtils.isEmpty(req.getEquipmentName()) ||
                !StringUtils.isEmpty(req.getSubsCode()) || !StringUtils.isEmpty(req.getEquipmentType()) ||
                !StringUtils.isEmpty(req.getCustName()) || !StringUtils.isEmpty(req.getCustAddress()) ||
                !StringUtils.isEmpty(req.getCustPhone()) || !StringUtils.isEmpty(req.getIndustryType())) {
            LatestLogListRequest request = new LatestLogListRequest();
            request.setImei(req.getImei());
            request.setEquipmentName(req.getEquipmentName());
            request.setSubsCode(req.getSubsCode());
            request.setCustName(req.getCustName());
            request.setCustAddress(req.getCustAddress());
            request.setCustPhone(req.getCustPhone());
            request.setIndustryType(req.getIndustryType());
            if (req.getEquipmentType() == null || StringUtils.isEmpty(req.getEquipmentType())) {
                //查询全部
                request.setEquipmentTypes(new String[]{EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode(),
                        EquipmentType.GAS_ALARM_CONTROLLER.getCode(), EquipmentType.HOME_GAS_DETECTOR.getCode(),
                        EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode()});
            } else {
                request.setEquipmentTypes(new String[]{req.getEquipmentType()});
            }
            request.setSpId(spId);
            equipmentList = equipmentService.queryEquipmentList(request);
            if (equipmentList.isEmpty()) {
                return new PageUtil(req.getPage(), req.getPageSize(), 0, resultList);
            }
        }
        List<Map<String, String>> imeiList = equipmentList.stream().map(a -> {
            Map<String, String> map = new HashMap();
            if (a.getEquipmentType().equals(EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode())) {
                map.put("imei", org.apache.commons.lang.StringUtils.substringBefore(a.getIMEI(), "-"));
                map.put("sub", org.apache.commons.lang.StringUtils.substringAfter(a.getIMEI(), "-"));
                return map;
            } else {
                if (a.getEquipmentType().equals(EquipmentType.GAS_ALARM_CONTROLLER.getCode())) {
                    map.put("sub", "__empty");
                } else {
                    map.put("sub", "1-1");
                }
                map.put("imei", a.getIMEI());
                return map;
            }
        }).collect(Collectors.toList());

        String where = "";
        String measurement = "select * from DataLogAsDetector where IsBroken=true and Path='" + path + "'";
        String measurementCount = "select count(ConsumerId) from DataLogAsDetector where IsBroken=true and Path='" + path + "'";
        if (!StringUtils.isEmpty(req.getTimeStart()) && !StringUtils.isEmpty(req.getTimeEnd())) {
            where = " and time>'" + req.getTimeStart() + "' and time<'" + req.getTimeEnd() + "'";
        }
        if (imeiList != null && !imeiList.isEmpty()) {
            StringBuffer dtuWhere = new StringBuffer();
            Map map = imeiList.get(0);
            dtuWhere.append(" and (DtuId='" + map.get("imei") + "'");
            for (int i = 1; i < imeiList.size(); i++) {
                Map map1 = imeiList.get(i);
                dtuWhere.append(" or DtuId='" + map1.get("imei") + "'");
            }
            dtuWhere.append(")");
            //sub参数拼接
            dtuWhere.append(" and (SubIdentifier='" + map.get("sub") + "'");
            for (int i = 1; i < imeiList.size(); i++) {
                Map map1 = imeiList.get(i);
                dtuWhere.append(" or SubIdentifier='" + map1.get("sub") + "'");
            }
            dtuWhere.append(")");
            where = where + dtuWhere;
        }
        String sort = " order by time desc limit " + req.getPageSize() + " offset " + (req.getPage() - 1) * req.getPageSize();
        //查询influxDb的AlertLog的总数
        String countSql = measurementCount + where;
        log.info(countSql);
        QueryResult countResult = influxDBConnect.query(countSql);

        Integer count = 0;
        if (countResult.getResults().get(0).getSeries() != null) {
            Double c = (Double) countResult.getResults().get(0).getSeries().get(0).getValues().get(0).get(1);
            count = c.intValue();
        }
        //分页查询influxDb的AlertLog
        String selectSql = measurement + where + sort;
        log.info(selectSql);
        QueryResult queryResult = influxDBConnect.query(selectSql);
        List<List<Object>> list = new ArrayList<>();
        if (queryResult.getResults().get(0).getSeries() != null) {
            list = queryResult.getResults().get(0).getSeries().get(0).getValues();
            log.info(list.toString());
        }
        List<String> imeis = new ArrayList<>();
        for (List<Object> objects : list) {
            BrokenLogResponse res = new BrokenLogResponse();
            res.setImei(objects.get(4).toString());
            res.setSubId(objects.get(10).toString());
            Double dtuType = Double.valueOf(objects.get(5).toString());
            if (Constants.DTU_TYPE_CONTROLLER.equals(dtuType.intValue())) {
                if ("__empty".equals(res.getSubId())) {
                    res.setImei(res.getImei());
                } else {
                    res.setImei(res.getImei() + "-" + res.getSubId());
                }
            } else {
                res.setImei(res.getImei());
            }
            res.setLatestTime(DateUtil.parse(objects.get(0).toString()));
            String reason = "发生故障";
            if (objects.get(5).toString().equals("5")) {
                JSONObject json = JSONUtil.parseObj(objects.get(8));
                if (json != null) {
                    if (Boolean.valueOf(json.get("bsB").toString())) {
                        reason = "总线短路";
                    }
                    if (Boolean.valueOf(json.get("mpb").toString())) {
                        reason = "主电故障";
                    }
                    if (Boolean.valueOf(json.get("bpb").toString())) {
                        if (StringUtils.isEmpty(reason)) {
                            reason = "备电故障";
                        } else {
                            reason = reason + ",备电故障";
                        }
                    }
                    if (Boolean.valueOf(json.get("cb").toString())) {
                        if (StringUtils.isEmpty(reason)) {
                            reason = "充电故障";
                        } else {
                            reason = reason + ",充电故障";
                        }
                    }
                }
            }
            res.setBrokenReason(reason);
            Integer consumerId = Double.valueOf(objects.get(1).toString()).intValue();
            res.setConsumerId(Integer.valueOf(consumerId));
            res.setId(DateUtil.parse(objects.get(0).toString()).getTime() * 1000000);
            imeis.add(res.getImei());
            resultList.add(res);
        }
        if (!imeis.isEmpty()) {
            LambdaQueryWrapper<Dtu> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.in(Dtu::getIMEI, imeis).eq(Dtu::getSpId, spId);
            if (req.getEquipmentType() == null || StringUtils.isEmpty(req.getEquipmentType())) {
                //查询全部
                queryWrapper.in(Dtu::getEquipmentType, new String[]{EquipmentType.INDEPENDENT_GAS_DETECTOR.getCode(),
                        EquipmentType.GAS_ALARM_CONTROLLER.getCode(), EquipmentType.HOME_GAS_DETECTOR.getCode(),
                        EquipmentType.POINT_TYPE_GAS_DETECTOR.getCode()});
            } else {
                queryWrapper.eq(Dtu::getEquipmentType, req.getEquipmentType());
            }
            //设备信息
            List<Dtu> dtuList = equipmentService.list(queryWrapper);
            log.info(dtuList.toString());
            //客户信息
            List<Integer> consumerIds = resultList.stream().map(BrokenLogResponse::getConsumerId).collect(Collectors.toList());
            LambdaQueryWrapper<Consumer> consumerQueryWrapper = new LambdaQueryWrapper<>();
            consumerQueryWrapper.eq(Consumer::getSpId, spId).in(Consumer::getId, consumerIds);
            List<Consumer> consumerList = consumerService.list(consumerQueryWrapper);

            for (BrokenLogResponse brokenLogResponse : resultList) {
                for (Dtu dtu : dtuList) {
                    if (dtu.getIMEI().equals(brokenLogResponse.getImei())) {
                        BeanUtils.copyProperties(dtu, brokenLogResponse);
                        DictionaryItemRespDTO dict = holder.getDictionaryByKey(
                                EquipmentType.DICT_CODE).stream().filter(a -> a.getValue().equals(
                                brokenLogResponse.getEquipmentType())).collect(Collectors.toList()).get(0);
                        brokenLogResponse.setEquipmentTypeName(dict.getName());
                        brokenLogResponse.setEquipmentName(dtu.getName() == null ? "" : dtu.getName());
                    }
                }
                for (Consumer consumer : consumerList) {
                    if (brokenLogResponse.getConsumerId().equals(consumer.getId())) {
                        brokenLogResponse.setSubsCode(consumer.getSubsCode());
                        brokenLogResponse.setIndustryType(consumer.getIndustryType());
                        brokenLogResponse.setCustName(consumer.getCustName());
                        brokenLogResponse.setCustAddress(consumer.getCustAddress());
                        brokenLogResponse.setCustPhone(consumer.getCustPhone());
                        //行业类型
                        if (!StringUtils.isEmpty(brokenLogResponse.getIndustryType())) {
                            DictionaryItemRespDTO communicationModeDict = holder.getDictionaryByKey(
                                    Constants.INDUSTRY_TYPE_CODE).stream().filter(a -> a.getValue().equals(
                                    brokenLogResponse.getIndustryType())).collect(Collectors.toList()).get(0);
                            brokenLogResponse.setIndustryType(communicationModeDict.getName());
                        }
                    }
                }
            }
        }
        PageUtil pageInfo = new PageUtil(req.getPage(), req.getPageSize(), count, resultList);
        return pageInfo;
    }

    @Override
    public HistoryBroken getImeiLastHistoryBroken(String spId, String imei, Integer consumerId) {
        LambdaQueryWrapper<HistoryBroken> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HistoryBroken::getIMEI,imei);
        queryWrapper.eq(HistoryBroken::getSpId,spId);
        queryWrapper.eq(HistoryBroken::getConsumerId,consumerId);
        queryWrapper.eq(HistoryBroken::getIsDeleted, 0);
        queryWrapper.orderByDesc(HistoryBroken::getId);
        queryWrapper.last("LIMIT 1");
        List<HistoryBroken> historyBrokenList = this.getBaseMapper().selectList(queryWrapper);
        log.info("alarmBrokenAutoHandelWhenRecovery historyBrokenList:{}", com.alibaba.fastjson.JSONObject.toJSONString(historyBrokenList));
        if (historyBrokenList == null || historyBrokenList.isEmpty()) {
            return null;
        }
        return historyBrokenList.get(0);
    }
}
